<?php

namespace App\Service\Moment;

use App\Constants\ErrorCode;
use App\Model\BlackWords;
use App\Model\Moment;
use App\Model\MomentComment;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Model\UserInteractMsg;
use App\Service\BaseService;

/**
 * 动态评论
 */
class MomentCommentService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $momentId = $this->request->input('moment_id', 0);
        $content = trim($this->request->input('content', ''));
        $commentId = $this->request->input('comment_id', 0);
        if (!$momentId || !$content) {
            return $this->setError(ErrorCode::PARAMETER_ERROR);
        }

        $check = BlackWords::checkLegal($content);
        if ($check['result'] != 1) {
            return $this->setError(ErrorCode::INPUT_SENSITIVE, '你的输入有违规文字，请重新输入～');
        }

        //拉黑关系
        $moment = Moment::find($momentId);
        if (!$moment) return $this->setError(ErrorCode::PARAMETER_ERROR, '该动态不存在～');

        //官方动态+拉黑不允许评论
        $checkBlack = UserBlacklist::check($moment->user_id, $userId);
        if (User::checkOfficial($moment->user_id) || $checkBlack) {
            return $this->setError(ErrorCode::CHAT_BLACK_LMT, '暂无法评论该动态~');
        }

        $commentedUserId = $parentCommentId = 0;
        if ($commentId) {
            $comment = MomentComment::find($commentId);
            if (!$comment) return $this->setError(ErrorCode::PARAMETER_ERROR, '回复的评论不存在！');
            $commentedUserId = $comment->commented_id ? $comment->user_id : 0;
            $parentCommentId = $comment->parent_comment_id ? $commentId : 0;
        }
        $result = MomentComment::create([
            'user_id' => $userId,
            'moment_id' => $momentId,
            'content' => $content,
            'commented_id' => $commentId,
            'parent_comment_id' => $parentCommentId,
            'commented_user_id' => $commentedUserId,
            'flag' => MomentComment::STATUS_OK,
        ]);
        //修改动态表comment_num字段
        Moment::updateCommentNum($momentId, 1);

        //消息记录
        UserInteractMsg::addMomentMsg($userId, $moment->user_id, $momentId, UserInteractMsg::TYPE_MOMENT_COMMENT, $content);
        log_user_result($userId, $result);
        return [
            'result' => 1,
            'comment' => MomentComment::buildItem($result->toArray(), $userId)
        ];
    }
}
